/*
Copyright 2013 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package mem provides access to bytes in memory.
package mem

import (
	"bytes"
	"errors"
	"io"
	"strings"
)

// RO is a read-only view of some bytes of memory. It may be be backed
// by a string or []byte and it may be revoked by the caller, to catch
// illegal callee uses after the end of documented validity periods.
//
// It should be passed around as a value type and is small (the same
// size as a slice).
type RO struct {
	// if b is non-nil, *b is used as the memory backing M.
	b *[]byte
	// if b is nil, s is used as the memory backing this M.
	s string

	// TODO: make an unsafe faster version of this all.
	// Also, consider adding a dummy func or slice field
	// to this struct just to make it not comparable.
}

// RB returns a read-only view of b.
func RB(b []byte) RO {
	return RO{b: &b}
}

// S returns a view of s.
func S(s string) RO {
	return RO{s: s}
}

func noop() {}

// Temp returns a version of v that is only valid until the returned
// revoke function is called.
func (v RO) Temp() (RO, Revoke) {
	if v.b != nil {
		s := *v.b
		return RO{b: &s}, func() { s = nil }
	}
	return v, noop
}

// Len returns the length of v.
func (v RO) Len() int {
	if v.b != nil {
		return len(*v.b)
	}
	return len(v.s)
}

func cloneBytes(b []byte) []byte {
	c := make([]byte, len(b))
	copy(c, b)
	return c
}

// ByteSlice returns a copy of the data as a byte slice.
func (v RO) ByteSlice() []byte {
	if v.b != nil {
		return cloneBytes(*v.b)
	}
	return []byte(v.s)
}

// String returns the data as a string, making a copy if necessary.
func (v RO) String() string {
	if v.b != nil {
		return string(*v.b)
	}
	return v.s
}

// At returns the byte at index i.
func (v RO) At(i int) byte {
	if v.b != nil {
		return (*v.b)[i]
	}
	return v.s[i]
}

// Slice returns a slice of v between the provided from and to indices.
func (v RO) Slice(from, to int) RO {
	if v.b != nil {
		s := (*v.b)[from:to]
		return RO{b: &s}
	}
	return RO{s: v.s[from:to]}
}

// SliceFrom slices v from the provided index until the end.
func (v RO) SliceFrom(from int) RO {
	if v.b != nil {
		s := (*v.b)[from:]
		return RO{b: &s}
	}
	return RO{s: v.s[from:]}
}

// SliceTo slices m from the provided index until the end.
func (v RO) SliceTo(to int) RO {
	return v.Slice(0, to)
}

// Copy copies v into dest and returns the number of bytes copied.
func (v RO) Copy(dest []byte) int {
	if v.b != nil {
		return copy(dest, *v.b)
	}
	return copy(dest, v.s)
}

// AppendTo appends v onto prefix and returns prefix (or an enlarged buffer).
func (v RO) AppendTo(prefix []byte) []byte {
	if v.b != nil {
		return append(prefix, (*v.b)...)
	}
	return append(prefix, v.s...)
}

// Equal reports whether the bytes in v are the same as the bytes in v2.
func (v RO) Equal(v2 RO) bool {
	if v2.b != nil {
		return v.EqualBytes(*v2.b)
	}
	return v.EqualString(v2.s)
}

// EqualString returns whether the bytes in b are the same as the bytes
// in s.
func (v RO) EqualString(s string) bool {
	if v.b == nil {
		return v.s == s
	}
	l := v.Len()
	if len(s) != l {
		return false
	}
	for i, bi := range *v.b {
		if bi != s[i] {
			return false
		}
	}
	return true
}

// EqualBytes returns whether the bytes in b are the same as the bytes
// in b2.
func (v RO) EqualBytes(b2 []byte) bool {
	if v.b != nil {
		return bytes.Equal(*v.b, b2)
	}
	l := v.Len()
	if len(b2) != l {
		return false
	}
	for i, bi := range b2 {
		if bi != v.s[i] {
			return false
		}
	}
	return true
}

// Reader returns an io.ReadSeeker for the bytes in v.
func (v RO) Reader() io.ReadSeeker {
	if v.b != nil {
		return bytes.NewReader(*v.b)
	}
	return strings.NewReader(v.s)
}

// ReadAt implements io.ReaderAt on the bytes in v.
func (v RO) ReadAt(p []byte, off int64) (n int, err error) {
	if off < 0 {
		return 0, errors.New("view: invalid offset")
	}
	if off >= int64(v.Len()) {
		return 0, io.EOF
	}
	n = v.SliceFrom(int(off)).Copy(p)
	if n < len(p) {
		err = io.EOF
	}
	return
}
